package com.shuqing.download.engine.distribute.dispatch.monitor.strategy;


import cn.hutool.core.util.StrUtil;
import com.shuqing.download.engine.DownLoadTaskDto;
import com.shuqing.download.engine.constants.TaskStatusEnum;
import com.shuqing.download.engine.distribute.dispatch.TaskContext;
import com.shuqing.download.engine.distribute.dispatch.monitor.Notify;
import com.shuqing.download.model.DownLoadTask;
import com.shuqing.download.service.owner.DownLoadTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 通知默认处理机制
 * @author wangshuqing
 * @date 2023/3/4 11:44
 */
@Component
public class DefaultNotifyHandler implements Notify {

    @Autowired
    private DownLoadTaskService taskService;

    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    @Override
    public void discover(TaskContext context, TaskStatusEnum statusEnum, String msg) {
        DownLoadTaskDto task=context.getTask();
        DownLoadTask update=new DownLoadTask();
        update.setId(task.getId());
        update.setTaskStatus(statusEnum.name());
        //如果成功或者失败的需要更新下时间
        if(statusEnum.equals(TaskStatusEnum.SUCCESS)
                || statusEnum.equals(TaskStatusEnum.FAIL)){
            //附件附件id
            update.setFileStoreId(context.getFileStoreId());
            //总耗时
            update.setConsumeTimes(context.getFullConsumeTime());
            //总条数
            update.setRowCount(context.getTotalSize());
            int maxLength=800;
            if(StrUtil.isNotBlank(msg) && msg.length()>maxLength){
                update.setErrorMsg(msg.substring(0,maxLength));
            }else{
                update.setErrorMsg(msg);
            }
            update.setErrorMsg(StrUtil.blankToDefault(msg,""));
        }
        taskService.updateById(update);
    }
}
